package com.lovegu.thread;

/**
 * @author 老顾
 * @title: CasTest
 * @projectName java-restudy
 * @email: 1437594522@qq.com
 * @date 2022/9/23 15:01
 */
public class CasTest {
    public volatile static int COUNT = 0;
    public synchronized static boolean compareAndSwap(int expect, int update) {
        if (expect == COUNT) {
            COUNT = update;
            return true;
        }
        return false;
    }
    public static void main(String[] args) throws InterruptedException {
        for (int j = 0; j < 100; j++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 模拟自旋
                while (!compareAndSwap(COUNT, COUNT + 1)){
                }
            }).start();
        }
        Thread.sleep(1000);
        System.out.println(COUNT);
    }
}
